import React, {useEffect, useState} from 'react';
import {Button, Form, Input, Modal, Select, Table, TableProps} from 'antd';
import type {ParkingArea} from "@/types/resp/parkingArea";
import parkingAreaApi from '@/api/parkingAreaApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import BuildingSelector from "@/pages/building/BuildingSelector.tsx";
import RoomSelector from "@/pages/room/RoomSelector.tsx";


interface ParkingAreaSelectorProps {
  visible: boolean;
  onParkingAreaSelected: (selectedParkingArea: { parkingAreaId?: number; parkingAreaNumber?: string; }) => void;
  onCloseParkingAreaSelector: () => void;
}

const ParkingAreaSelector: React.FC<ParkingAreaSelectorProps> = ({visible, onParkingAreaSelected, onCloseParkingAreaSelector}) => {

  const [parkingAreaSelectorForm] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    parkingAreaSelectorForm.resetFields();
  };

  const [data, setData] = useState<ParkingArea[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<ParkingArea>> = await parkingAreaApi.find(parkingAreaSelectorForm.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<ParkingArea> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<ParkingArea>['columns'] = [
    {title: '车位号', dataIndex: 'areaNumber', key: 'areaNumber'},
    {title: '楼栋名称', dataIndex: 'buildingName', key: 'buildingName'},
    {title: '所在楼层', dataIndex: 'floorNumber', key: 'floorNumber'},
    {title: '单元房号', dataIndex: 'residentRoomNumber', key: 'residentRoomNumber'},
    {title: '车牌', dataIndex: 'licensePlate', key: 'licensePlate'},
    {title: '状态', key: 'status', render: (_, record) => (
        <span>
        {(function () {
          if (record.status === 30) return '临停';
          else if (record.status === 10) return '业主';
          else if (record.status === 20) return '月租';
          else return '未知';
        })()}
      </span>
      ),
    },
  ];

  const handleRowDoubleClick = (row: ParkingArea) => {
    onParkingAreaSelected({
      parkingAreaId: row.id,
      parkingAreaNumber: row.areaNumber,
    })
  };

  const selectorFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onCloseParkingAreaSelector}>关闭</Button>
    </div>
  );

  useEffect(() => {
    if (visible) {
      onSearch();
    }
  }, [visible]);

  const [buildingSelectorVisible, setBuildingSelectorVisible] = useState(false);
  const findBuilding = () => {
    setBuildingSelectorVisible(true);
  }
  const handleBuildingSelected = (selectedBuilding: { buildingId?: number; buildingName?: string; }) => {
    setBuildingSelectorVisible(false)
    if (selectedBuilding && 'buildingId' in selectedBuilding) {
      parkingAreaSelectorForm.setFieldsValue(Object.assign(parkingAreaSelectorForm.getFieldsValue(), {
      buildingId: selectedBuilding['buildingId'],
      buildingName: selectedBuilding['buildingName'],
      }));
    }
  };
  const handleCloseBuildingSelector = () => {
    setBuildingSelectorVisible(false)
  };
  const [roomSelectorVisible, setRoomSelectorVisible] = useState(false);
  const findRoom = () => {
    setRoomSelectorVisible(true);
  }
  const handleRoomSelected = (selectedRoom: { residentRoomId?: number; residentRoomNumber?: string; }) => {
    setRoomSelectorVisible(false)
    if (selectedRoom && 'residentRoomId' in selectedRoom) {
      parkingAreaSelectorForm.setFieldsValue(Object.assign(parkingAreaSelectorForm.getFieldsValue(), {
      residentRoomId: selectedRoom['residentRoomId'],
      residentRoomNumber: selectedRoom['residentRoomNumber'],
      }));
    }
  };
  const handleCloseRoomSelector = () => {
    setRoomSelectorVisible(false)
  };

  return (
    <Modal title={"车位信息选择器(双击行选中)"} open={visible} onCancel={onCloseParkingAreaSelector}
        width={'var(--modal-width)'} footer={selectorFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      <Form form={parkingAreaSelectorForm} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="areaNumber" label="车位号">
          <Input maxLength={32} placeholder="请输入车位号"/>
        </Form.Item>
        <Form.Item name="buildingName" label="楼栋名称">
          <Input.Search placeholder="请选择楼栋名称" onSearch={findBuilding} readOnly={true} />
        </Form.Item>
        <Form.Item name="floorNumber" label="所在楼层">
          <Input maxLength={32} placeholder="请输入所在楼层"/>
        </Form.Item>
        <Form.Item name="residentRoomNumber" label="单元房号">
          <Input.Search placeholder="请选择单元房号" onSearch={findRoom} readOnly={true} />
        </Form.Item>
        <Form.Item name="licensePlate" label="车牌">
          <Input maxLength={32} placeholder="请输入车牌"/>
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select placeholder="请选择状态" options={[
            { value: 30, label: <span>临停</span> },
            { value: 10, label: <span>业主</span> },
            { value: 20, label: <span>月租</span> }
          ]} style={{width: 'var(--select-width)'}} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
      </Form>
      <Table<ParkingArea> columns={columns} dataSource={data} size="small" rowKey={record => record.id}
                         pagination={{ position: ["bottomCenter"] }}
                         onRow={(row) => ({
                           onDoubleClick: (event) => {
                             event.preventDefault();
                             handleRowDoubleClick(row);
                           },
                         })}/>
      <BuildingSelector visible={buildingSelectorVisible} onBuildingSelected={handleBuildingSelected} onCloseBuildingSelector={handleCloseBuildingSelector} />
      <RoomSelector visible={roomSelectorVisible} onRoomSelected={handleRoomSelected} onCloseRoomSelector={handleCloseRoomSelector} />
    </Modal>
  );
};

export default ParkingAreaSelector;
